<template>
	<view class="manager" :style="{ height: `${windowHeight}px`, width: `${windowWidth}px` }">
		<view class="card-mask" :style="{ height: `${windowHeight}px`, width: `${windowWidth}px` }" v-if="dataList.length == 0 && userToken && canGain && !firstGain">
			<view class="card-mask-popup" :style="{ backgroundImage: `url(${staticFileDomain}/static/image/card-mask.png)` }">
				<template>
					<view class="card-mask-popup-tips">暂无更多匹配会员了</view>
					<view class="card-mask-popup-title" @tap.stop="refreshData">刷新</view>
				</template>
				<!-- <view class="card-mask-popup-tips">暂无更多匹配会员了</view> -->
			</view>
		</view>
		<view class="move-area" :style="{ height: `${windowHeight - topSpaceHeight}px` }" v-if="!userToken">
			<view class="move-view"><photo-card class="photoCard" ref="loginBox" type="login"></photo-card></view>
		</view>
		<!-- #ifdef APP-VUE || MP-WEIXIN || H5 -->
		<block v-else>
			<view class="move-area" :style="{ height: `${windowHeight - topSpaceHeight}px` }" v-if="instruct" v-for="(instruct, hand) in wxsCompatible" :key="hand">
				<block v-for="(item, index) in dataList" :key="item.guid">
					<view
						v-if="index <= thresholdShow"
						class="move-view"
						:class="{ 'will-change': index <= 1 }"
						@touchend="slide.touchend"
						@tap.stop="tapCard(item)"
						@touchmove="slide.touchMove"
						@touchstart="slide.touchStart"
						:animation="animationData[index]"
						:data-window-size="windowSize"
						:data-index="index"
						:style="{
							transform: index < thresholdShow ? ` scale(${1 - (1 - scale.x) * index},${1 - (1 - scale.y) * index})  translate(${translate.x * index}px, ${translate.y * index}px)` : ` scale(${1 - (1 - scale.x) * (thresholdShow - 1)},${1 - (1 - scale.y) * (thresholdShow - 1)})  translate(${translate.x * (thresholdShow - 1)}px, ${translate.y * (thresholdShow - 1)}px)`,
							zIndex: `${999 - item._id}`,
							opacity: index < thresholdShow ? `${1 - (1 - opacity) * index}` : `${1 - (1 - opacity) * (thresholdShow - 1)}`
						}"
					>
						<photo-card class="photoCard" :index="index" :card="item" ref="cardBox"></photo-card>
					</view>
				</block>
			</view>
		</block>
		<!-- #endif -->
	</view>
</template>
<script src="./wxs/slide.wxs" module="slide" lang="wxs"></script>
<script>
import photoCard from '@/components/photo-card/photo-card.vue';
export default {
	components: { photoCard },
	data() {
		return {
			windowHeight: null,
			windowWidth: null,
			topSpaceHeight: null,
			thresholdShow: 3,
			delMoveDistance: null,
			scale: { x: 0.95, y: 1 },
			translate: { x: 0, y: 8 }, //y下移
			opacity: 1, //透明度，参数范围 0~1
			touchAnimation: null,
			animationData: {},
			dataList: [],
			delTime: 150,
			cardId: 0,
			windowSize: { width: null, height: null },

			latitude: null,
			longitude: null,
			//消除wxs在app上绝对有失效的问题
			wxsCompatible: {
				a: true
			},
			canGain: true,
			firstGain: true,
			thresholdGain: 5,
			//定位完成
			locationComplete: false
		};
	},
	watch: {
		thresholdShow: {
			immediate: true,
			handler(newVal, oldVal) {
				for (var i = 0; i < newVal; i++) {
					let a = {};
					a[i] = {};
					this.animationData = { ...this.animationData, ...a };
				}
			}
		},
		dataList: {
			handler(newVal, oldVal) {
				for (let item of newVal) {
					if (!item._id) {
						item._id = this.cardId++;
					}
				}
			}
		}
	},
	beforeMount() {
		this.initView();
		// #ifdef H5
		uni.onWindowResize(res => {
			setTimeout(() => {
				this.initView();
			}, 300);
		});
		// #endif
	},

	beforeDestroy() {
		uni.$off('windowResize', this.initView);
	},
	async mounted() {
		// #ifdef APP-PLUS
		this.wxsCompatible = {
			a: true,
			b: false
		};
		// #endif
		this.createAnimation();

		if (this.isLogin()) {
			await this.getData();
		}
	},

	methods: {
		async refreshData() {
			this.cardId = 0;
			this.dataList = [];
			this.locationComplete = false;
			setTimeout(async () => {
				await this.getData();
			}, 0);
		},
		initView() {
			const systemInfo = uni.getSystemInfoSync();
			this.windowWidth = systemInfo.windowWidth;
			this.windowHeight = systemInfo.windowHeight;
			this.windowSize = JSON.stringify({ width: this.windowWidth, height: this.windowHeight });
			this.delMoveDistance = systemInfo.windowHeight;
			this.topSpaceHeight = 44 + systemInfo.statusBarHeight;
		},
		createAnimation() {
			//touch移动动画
			this.touchAnimation = uni.createAnimation({
				duration: 0
			});
			//其他卡片移动
			this.moveAnimation = uni.createAnimation({
				duration: 0
			});
			//删除动画
			this.delanimation = uni.createAnimation({
				duration: this.delTime
			});
			//删除时其他card动画
			this.endanimation = uni.createAnimation({
				duration: 200
			});
		},

		//获取数据
		async getData() {
			if (this.canGain && this.isLogin()) {
				if (!this.locationComplete) {
					uni.getLocation({
						success: async res => {
							if (res.errMsg == 'getLocation:ok') {
								await this.$u.api.updateLngLat(res.longitude, res.latitude);
								this.getCard();
							} else {
								this.getCard();
							}
						},
						fail: () => {
							this.getCard();
						},
						complete: () => {
							this.locationComplete = true;
						}
					});
				} else {
					this.getCard();
				}
			}
		},
		getCard() {
			this.canGain = false;
			this.$u.api
				.getCoupCardList()
				.then(res => {
					let dataGroup = [];
					const list = res.data.list;
					this.initData(list);
					setTimeout(() => {
						this.canGain = true;
						this.firstGain = false;
					}, 0);
				})
				.catch(e => {
					this.canGain = true;
					this.firstGain = false;
				});
		},
		//触摸中判断
		moveJudge(arg) {
			let el = this.$refs.cardBox[0];
			if (arg.x > 20) {
				el.moveRight(arg.ratio);
			} else if (arg.x < -20) {
				el.moveLeft(arg.ratio);
			} else {
				el.moveCenter();
			}
		},
		//卡片位置重置
		cardPositionReset(arg) {
			let cardBox = this.$refs.cardBox[0];
			if (Math.abs(arg.moveY) >= 100) {
				cardBox.toUserDetail();
			}
			cardBox.reset();
			setTimeout(() => {
				//清除动画
				this.animationData[0] = this.delanimation.export();
				for (var i = 1; i < this.thresholdShow; i++) {
					this.animationData[i] = this.moveAnimation.export();
				}
			}, arg.animationTime);
		},
		moveDeleteCard(arg) {
			this.delCard(arg.x, arg.y);
			setTimeout(() => {
				//清除动画
				this.animationData[0] = this.delanimation.export();
				for (var i = 1; i < this.thresholdShow; i++) {
					this.animationData[i] = this.moveAnimation.export();
				}
				if (this.dataList.length <= this.thresholdGain) {
					this.getData();
				}
			}, arg.animationTime);
			// #ifdef APP-PLUS
			if (this.wxsCompatible.a) {
				this.wxsCompatible = { a: false, b: true };
			} else {
				this.wxsCompatible = { a: true, b: false };
			}
			// #endif
		},
		//删除card时
		delCard(x, y) {
			if (x > 0) {
				console.log(this.dataList[0], '喜欢');
				this.$emit('slideToRight', this.dataList[0]);
			} else {
				console.log(this.dataList[0], '不喜欢');
				this.$emit('slideToLeft', this.dataList[0]);
			}
			this.dataList.splice(0, 1);
		},
		tapCard(item) {
			this.$refs.cardBox[0].toUserDetail();
		},
		touchAnimationStep(arg) {
			//其他card动画
			let ratio = arg.ratio;
			let animationData = {};
			for (var i = 1; i < this.thresholdShow; i++) {
				const diff = i - ratio;
				if (this.scale.x != 1) this.moveAnimation.scaleX(1 - (1 - this.scale.x) * diff);
				if (this.scale.y != 1) this.moveAnimation.scaleY(1 - (1 - this.scale.y) * diff);
				if (this.translate.x != 0) this.moveAnimation.translateX(this.translate.x * diff);
				if (this.translate.y != 0) this.moveAnimation.translateY(this.translate.y * diff);
				this.moveAnimation.step();
				animationData[i] = this.moveAnimation.export();
			}
			this.animationData = animationData;
			//触摸中视图变化
			// this.moveJudge(this.moveX, this.moveY, ratio);
		},
		initData(list) {
			const dataGroup = [];
			for (var i = 0; i < list.length; i++) {
				const item = list[i];
				dataGroup.push({
					guid: this.$u.guid(),
					avatar: item.avatar,
					sex: item.gender,
					city: item.city,
					province: item.province,
					score: item.score,
					district: item.district,
					distance: item.distance,
					nickName: item.nickName,
					label: item.label,
					isVip: item.is_vip == 1,
					age: item.birth_age || item.idcard_age,
					moveX: 0,
					moveY: 0,
					isFollow: item.follow,
					userId: item.user_id,
					animation: false
				});
			}
			this.dataList.push(...dataGroup);
		}
	}
};
</script>

<style lang="scss">
.manager {
	position: relative;
	.move-area {
		width: 100%;
		left: 0;
		margin-top: calc(44px + var(--status-bar-height));
		position: absolute;
		.move-view {
			position: absolute;
			width: 100%;
			height: 100%;
			display: flex;
			align-items: center;
			justify-content: center;
		}
	}
}
.card-mask {
	background-color: rgba(255, 255, 255, 0);
	position: absolute;
	top: calc(44px + var(--status-bar-height));
	z-index: 1000;

	.card-mask-popup {
		position: absolute;
		top: 0;
		bottom: 340rpx;
		left: 50%;
		margin-left: -283rpx;
		width: 566rpx;
		background-position: bottom center;
		background-size: cover;
		display: flex;
		flex-direction: column;
		justify-content: flex-end;
		align-items: center;
		.card-mask-popup-tips {
			color: $theme-main-color;
			font-size: 26rpx;
			margin-bottom: 30rpx;
		}
		.card-mask-popup-title {
			width: 400rpx;
			height: 80rpx;
			border-radius: 40rpx;
			background: linear-gradient(180deg, rgba(237, 79, 93, 1) 0%, rgba(251, 122, 142, 1) 100%);
			color: #fff;
			font-size: 34rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			margin-bottom: 40rpx;
		}
	}
}
.will-change {
	will-change: transform;
}
</style>
